<?php
/**
 * Class Bank
 * Desc  银行卡
 * Create on 2023/4/23 17:14
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use think\Db;
use think\exception\ValidateException;

class Bank extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected $model = '';

    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\xyb\Bank();
    }

    //添加银行卡
    public function add()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $params = $this->request->post();
        $params['user_id'] = $this->auth->id;
        $count = $this->model->where('user_id',$params['user_id'])->count();
        if ($count > 0) {
            $this->error('已添加银行卡');
        }
        Db::startTrans();
        try {
            $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            $validate = $name . '.add';
            $this->model->validateFailException(true)->validate($validate);

            $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }  catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功',['id'=>$this->model->id]);

    }

    //编辑银行卡
    public function edit()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $params = $this->request->post();
        $row = $this->model->where('user_id',$this->auth->id)->find();
        Db::startTrans();
        try {
            $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            $validate = $name . '.edit';
            $row->validateFailException(true)->validate($validate);

            $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    //银行卡详情
    public function detail()
    {
        $bankObj = $this->model->where('user_id',$this->auth->id)->find();
        if($bankObj) {
            $bankObj->hidden(['user_id','id']);
        }
        $this->success('请求成功',$bankObj);
    }
}



 